from generate_slide_image_v2_1 import generate_slide_image
import json, sys, os, traceback
from flask import Flask, request
from flask_cors import CORS


###########################################

# Use Demo

###########################################
app = Flask(__name__,static_folder=os.getcwd()+'/images')
g = dict()
@app.route('/api/slide/image/create', methods=['GET'])
def get_slide_image():
    """获取拖拉图片及uuid

    Returns:
        _type_: 返回拖拉图片及uuid
    """
    data = generate_slide_image("./images/original/bg16.png")
    g[data['uuid']] = {
        'slide_rate': data['slide_rate'],#偏移率
        'slide_width': data['slide_width']#偏移量
    }
    del data['slide_rate']
    del data['slide_width']
    return data

@app.route('/api/slide/image/verify/width', methods=['POST'])
def verify_width():
    """认证偏移距离

    Returns:
        _type_: 返回认证结果
    """
    requests = request.get_json()
    uuid = requests['uuid']
    slide_width = requests['slide_width']
    try:
        data = g[uuid]
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        error_trace = traceback.format_exception(exc_type, exc_value, exc_traceback)
        return {"status":False, "error": json.dumps(error_trace)}
    status = False
    if (slide_width > (data['slide_width']-5)) and (slide_width < (data['slide_width']+5)):
        status = True
    del g[uuid]
    return {"status":status}

@app.route('/api/slide/image/verify/rate', methods=['POST'])
def verify_rate():
    """认证偏移率

    Returns:
        _type_: 返回认证结果
    """
    requests = request.get_json()
    uuid = requests['uuid']
    slide_rate = requests['slide_rate']
    data = g[uuid]
    status = False
    if slide_rate == data['slide_rate']:
        status = True
    del g[uuid]
    return status
    


if __name__ == '__main__':
    CORS(app, supports_credentials=True)
    app.debug = False
    app.run(host='0.0.0.0', port=500)